package com.xk.service.impl;

import com.xk.mapper.ClassMapper;
import com.xk.mapper.TeacherMapper;
import com.xk.pojo.Classes;
import com.xk.pojo.Page;
import com.xk.pojo.Teacher;
import com.xk.service.ClassesService;
import com.xk.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassMapper mapper;

    @Override
    public List<Classes> getAllClasses() {

        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        mapper = sqlSession.getMapper(ClassMapper.class);
        List<Classes> classes = mapper.getAllClasses();
        sqlSession.close();
        return classes;
    }



    @Override
    public int deleteClassById(Integer id) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        mapper = sqlSession.getMapper(ClassMapper.class);
        int i = mapper.deleteClassById(id);
        sqlSession.commit();
        sqlSession.close();
        return i;    }

    @Override
    public int updateClassesById(Classes classes) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        mapper = sqlSession.getMapper(ClassMapper.class);
        int i = mapper.updateClassesById(classes);
        List<Classes> classes1 = mapper.getClassesByTeacherID(classes.getTeacherID());
        //一个班级只有一个班主任，如果有两个就取消更新
        if (classes1.size()!=1){
            sqlSession.rollback();
            i=-1;
        }else
            sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public String addClass(Classes classes) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        mapper = sqlSession.getMapper(ClassMapper.class);
        int i = mapper.addClass(classes);


        sqlSession.commit();
        sqlSession.close();
        if (i==1)
            return "添加成功";
        else
            return "添加失败";
    }

    @Override
    public Page<Classes> getClassesListByPage(int pageNumber, int pageSize, String search) {
        System.out.println("ClassServiceImpl");
        System.out.println("pageNumber:"+pageNumber+" pageSize："+pageSize+" search:"+search);
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        mapper = sqlSession.getMapper(ClassMapper.class);
        List<Classes> classes;
        if (search.equals("")||search==null){
            classes = mapper.getAllClasses();
        }else {
            classes=mapper.getClassesByName(search);
        }

        Page page=new Page(pageNumber,pageSize,classes.size());
        System.out.println();
        List<Classes> classesList
                = mapper.getClassesListByPage((pageNumber - 1) * pageSize,
                pageSize,search);

        page.setDataList(classesList);

        sqlSession.close();
        return page;
    }


}
